package com.meizu.llp.cameratest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by llp on 16-11-16.
 */

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{

    public SurfaceHolder mHolder;
    private Camera mCamera;

    //创建一个surface来preview camera
    public CameraPreview(Context context,Camera camera) {
        super(context);
        mHolder = this.getHolder();
        mCamera = camera;
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public SurfaceHolder getSurfaceHolder(){
        if (mHolder!=null){
            return mHolder;
        }else {
            return null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();//启动preview
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        if (mHolder==null){
            return;
        }
        //当surface发生改变的时候，先关闭掉preview，然后再次启动
        mCamera.stopPreview();
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();//启动preview
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        System.out.println("surfaceDestroyed");
    }

}
